import LangEn from '@/lang/en.js'
import LangCn from '@/lang/cn.js'
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)

const system_info = uni.getStorageSync('system_info')
const getLocalLang = uni.getStorageSync('YYG_LANG')

if (!system_info) {
    // 获取设备信息
    uni.getSystemInfo({
        success: function (res) {
            uni.setStorageSync('system_info', res);
        }
    })
}

let cur_lang = ''
if (getLocalLang) {
	cur_lang = getLocalLang
} else {
	cur_lang = 'en'
	uni.setStorageSync('YYG_LANG', 'en')
}

const i18n = new VueI18n({
	locale: cur_lang || 'en',
	messages: {  
		'en': LangEn,
		'cn': LangCn
	}
})

import {
	HTTP_LOTTERY_REQUEST_URL,
	HEADER,
	TOKENNAME,
	HEADERPARAMS
} from '@/config/app';
import {
	toLogin,
	checkLogin
} from '../libs/login';
import store from '../store';

/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}, params) {
	let Url = HTTP_LOTTERY_REQUEST_URL,header = HEADER
	// let Url = "http://yyg.sosshell.com",header = HEADER
	if (params != undefined) {
		header = HEADERPARAMS;
	}
	console.log("noauth"+noAuth);
	if (!noAuth) {
		//登录过期自动登录
		if (!store.state.app.token && !checkLogin()) {
			toLogin();
			return Promise.reject({
				// '未登录'
				msg: getLocalLang ? i18n.messages[getLocalLang].index.common.no_log : i18n.messages['en'].index.common.no_log
			});
		}
	}

	if (store.state.app.token) header[TOKENNAME] = "hlg_"+store.state.app.token;

    header['content-type']="application/x-www-form-urlencoded;charset=utf-8;";

	return new Promise((reslove, reject) => {
		//Url="http://10.52.164.235:8081/pinbao";
		//console.debug(Url + '/api/front/' + url);
		
		uni.request({
			url: Url + '/api/' + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				if (noVerify)
					reslove(res.data, res);
				else if (res.statusCode == 200)
					reslove(res.data, res);
				else if ([410000, 410001, 410002, 401].indexOf(res.data.code) !== -1) {
					toLogin();
					reject(res.data);
				} else
					// reject(res.data.message || '系统错误');
					reject(res.data.message || 'system error');
			},
			fail: (msg) => {
				reject('Request failed');
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt, params) => baseRequest(api, method, data, opt || {}, params)
});



export default request;
